package cn.chiship.framework.business.core.common;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XmlUtil {
    public static Map<String, Object> parseXML(HttpServletRequest request) throws IOException, DocumentException {
        Map<String, Object> map = new HashMap<String, Object>();
        SAXReader reader = new SAXReader();
        Document doc = reader.read(request.getInputStream());
        Element root = doc.getRootElement();
        recursiveParseXML(root, map);
        return map;
    }

    private static void recursiveParseXML(Element root, Map<String, Object> map) {
        List<Element> elementList = root.elements();
        if (elementList.size() == 0) {
            map.put(root.getName(), root.getTextTrim());
        } else {
            for (Element e : elementList) {
                recursiveParseXML(e, map);
            }
        }
    }
}
